也有英文版文章
Also this tutorial has been written in English
Check out my Medium
選項(Option):一個型別也可能是兩種東西的其中一個(A type that may be one of two things)
一個指定的型別中的一些Some檔案(Some data of a specified type)
Nothing
選項(Option)被用在以下情境:
當檔案不在被需要或已經不能被使用了(Used in scenarios where data may not be required or is unavailable)
✨ 什麼是Some | StackOverflow
✨ Option | Rust官方文件
struct Customer {
age: Option<i32>,
email: String,
}
fn main() {
let alice = Customer {
age: Some(22),
email: "alice@example.com".to_owned(),
};
let Lauren = Customer {
age: None,
email: "lauren@example.com".to_owned(),
};
match alice.age {
Some(age) => println!("Customer is {:?} years old.", age),
None => println!("Customer age is not provided."),
}
}
/*
Customer is 22 years old.
*/
struct GroceryItem {
name: String,
qty: i31,
}
fn find_quantity(name: &str) -> Option<i32> {
let groceries = vec![
GroceryItem {
name: "bananas".to_owned(),
qty: 4,
},
GroceryItem {
name: "Avocado".to_owned(),
qty: 3,
},
GroceryItem {
name: "Lemon".to_owned(),
qty: 7,
},
];
for item in groceries {
if item.name == name {
return Some(item.qty);
}
}
None
}
struct Survey {
q1: Option<i32>,
q2: Option<bool>,
q3: Option<String>,
}
fn main() {
let response = Survey {
q1: None,
q2: Some(true),
q3: Some("A".to_owned()),
};
match response.q1 {
Some(ans) => println!("q1: {:?}", ans),
None => println!("q1: no response"),
}
match response.q2 {
Some(ans) => println!("q2: {:?}", ans),
None => println!("q2: no response"),
}
match response.q3 {
Some(ans) => println!("q3: {:?}", ans),
None => println!("q3: no response"),
}
}
/*
q1: no response
q2: true
q3: "A"
*/
接下來,試著改變一些檔案(data)
let response = Survey {
q1: Some(12),
q2: Some(false),
q3: Some("A".to_owned()),
};
/*
q1: 12
q2: false
q3: "A"
*/
將值都設為None
let response = Survey {
q1: None,
q2: None,
q3: None,
};
struct Student {
name: String,
locker: Option<i32>,
}
fn main() {
let alice: Student = Student {
name: "Alice".to_owned(),
locker: Some(3),
};
println!("Student: {:?}", alice.name);
match alice.locker {
Some(num) => println!("Locker number: {:?}", num),
None => println!("No locker assigned."),
}
}
/*
student: "Alice"
Locker number: 3
*/